package com.xunyun.kotlinwc.network.response

import com.xunyun.kotlinwc.network.exception.ApiException
import com.xunyun.kotlinwc.network.exception.ErrorCodeConstant
import com.xunyun.kotlinwc.network.exception.ExceptionUtil
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers

import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers

/**
 * @author gl
 * @date 2021/9/8
 * @desc
 */
class ResponseTransformer<T> : ObservableTransformer<ResponseData<T>, T> {
    override fun apply(upstream: Observable<ResponseData<T>>): ObservableSource<T> {
        return upstream.onErrorResumeNext { throwable: Throwable? ->
            Observable.error(ExceptionUtil.handleException(throwable))
        }
            .flatMap(Function<ResponseData<T>?, ObservableSource<T>> {
                if (it.errorCode == 0 ) {
                    if (null != it.data){
                        return@Function Observable.just(it.data)
                    }else{
                        //返回数据为空时 数据处理
                        try {
                            val clazz: Class<*> = it::class.java
                            val field = clazz.getDeclaredField("data")
                            val obj = field.declaringClass.newInstance() as T
                            return@Function Observable.just(obj)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
                return@Function Observable.error(
                    ApiException(ErrorCodeConstant.UNKNOWN_ERROR, "未知错误")
                )
            }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

    }



}






